jQuery.noConflict();

    // Thanks for this code snippet from http://www.tutorials.de/
var HTTP_GET_VARS = new Array();
var strGET = document.location.search.substr(1, document.location.search.length);
if (strGET != '') {
    var gArr = strGET.split('&');
    var i;
    for (i = 0; i < gArr.length; ++i) {
        var v = '';var vArr = gArr[i].split('=');
        if (vArr.length > 1) { v = vArr[1]; }
        HTTP_GET_VARS[unescape(vArr[0])] = unescape(v);
    }
}

function GET(v) {
    if (!HTTP_GET_VARS[v]) { return 'undefined'; }
    return HTTP_GET_VARS[v];
}

var url             = decodeURIComponent(GET("url"));
var method          = decodeURIComponent(GET("method"));
var params          = JSON.parse(decodeURIComponent(GET("params")));
var sessionid_name  = decodeURIComponent(GET("sessionidname"));
var sessionid_arr = [];
var spawning = true;
var counter = 0;
var total_ids = 0;
var n; // Gewuenschte Anzahl SessionIDs
var cookie_secure_warning = false;
var cookie_domain_warning = false;
var HSTS_header_warning = false;
         
function id(id) {
    return document.getElementById(id);
}

function bg() {

    return chrome.extension.getBackgroundPage();
}

function stopSpawning() {
    spawning = false;
    id("sessionid_spawn_button").setAttribute("style", "display:block;");
    id("stop_spawning_button").setAttribute("style", "display:none;");
}

function getCookie_and_HSTS_header() {
    // durch onload() Listener des iFrames getriggert
    chrome.cookies.get({ url: url, name: sessionid_name }, function (cookie) {
        if (cookie != null) {
            //alert(JSON.stringify(cookie.value));
            counter++;
            total_ids++;
            id("spawn_results").value += cookie.value + "\r\n";
            id("progress").innerHTML = "<font color='green'>Collected:" + total_ids + "</font>";
            if (url.substr(0, 5).toLowerCase() === "https" && !cookie.secure && !cookie_secure_warning) {
                cookie_secure_warning = true;
                var font = document.createElement("font");
                font.color = "red";
                font.innerHTML = "WARNING: Session cookie is set as response to HTTPS request but <i>Secure</i> attribute is not set.<br/>";
                id("warning_div").appendChild(font);
            }
            else if(!cookie_secure_warning) {
            	cookie_secure_warning = true;
               var font = document.createElement("font");
               font.color = "green";
               font.innerHTML = "<i>Secure</i> attribute of session cookie is set.<br/>";
               id("warning_div").appendChild(font);
            }
            if (!cookie_domain_warning && cookie.domain.toString().substr(0, 1) === "." && url.substr(0, 5).toLowerCase() === "https") {
                cookie_domain_warning = true;
                var font = document.createElement("font");
                font.color = "red";
                font.innerHTML = "WARNING: Cookie is sent to all subdomains: <i>Domain</i> = " + cookie.domain.toString() + "<br/>";
                id("warning_div").appendChild(font);
            }
            else if (!cookie_domain_warning) {
                cookie_domain_warning = true;
                var font = document.createElement("font");
                font.color = "green";
                font.innerHTML = "<i>Domain</i> attribute : " + cookie.domain.toString() + "<br/>";
                id("warning_div").appendChild(font);
            }
            // look if HSTS header detected in background Script 
				if(!HSTS_header_warning) {            
            	if(bg().HSTS_header !== null) {
			    		var font = document.createElement("font");
						if(bg().HSTS_header.indexOf("not found") != 0) {    	
   			 			font.color = "red";
    						font.innerHTML = bg().HSTS_header + "<br/>";    		
    					}
    					else {
    						font.color = "green";
    						font.innerHTML = bg().HSTS_header + "<br/>";
    					}
    					id("warning_div").appendChild(font);
    					HSTS_header_warning = true;
    				}
    			}	
            spawnNext();
        }
    });           

};
        

function spawnSessionIDs() {
    // TODO: mit jquery Fortschrittsanzeige
    spawning = true;
    counter = 0;
    n = parseInt(id("num_sessionids").value);

    id("sessionid_spawn_button").setAttribute("style", "display:none;");
    id("stop_spawning_button").setAttribute("style", "display:block;");
    spawnNext(); // Starte Rekursion, Timing evtl. kritisch?
    id("check_distribution_button").style.display = "block";
    id("spawn_results").style.width = "500px";
    id("spawn_results").style.height = "600px";
    id("spawn_results").style.display = "block";
    
    
}

function spawnNext() {
    //alert("spawnNext()");
    if (counter < n && spawning) {
        chrome.cookies.remove({ url: url, name: sessionid_name }, function (details) {
            if (details == null) {
                alert("Error spawning cookies: Cannot remove cookie");
            }
        });
        submitFormInIFrame(params); // Cookie anfragen NACHDEM dieser iframe geladen wurde, standartmaessig wird naechste funktion vor dieser aufgerufen
    }
    else {
        id("sessionid_spawn_button").setAttribute("style", "display:block;");
        id("stop_spawning_button").setAttribute("style", "display:none;");
    }
    // sonst stoppe, kein neuer iframe und neues submit()
}

function submitFormInIFrame(param_arr) {
    // formular muss in iframe abgesendet werden, bei xmlhttp request wird keine neue sessionid vergeben wenn diese geloescht
    // TODO: was wenn keine Parameter
            
            
    if (param_arr.length > 0) {
        // same origin policy muss stimmen daher neuer iframe
        id("spawn_div").removeChild(id("spawn_iframe"));
        ifr = document.createElement("iframe");
        ifr.onload = getCookie_and_HSTS_header;
        ifr.id = "spawn_iframe";
        ifr.style.display = "none";
        ifr.width = "1px";
        ifr.height = "1px";
        id("spawn_div").appendChild(ifr);

        //frames["spawn_iframe"].src = ""; // geht nicht mit same orig policy
        //frames["spawn_iframe"].location.reload();
        var doc = frames["spawn_iframe"].document;
        var content = document.createElement("div"); // nur temporaer
        var html = document.createElement("html");
        var form = document.createElement("form");
        form.method = method;
        form.action = url;
        form.id = "spawn_form";
        for(i = 0; i < param_arr.length; i++) {
            var input = document.createElement("input");
            input.type = "hidden";
            input.name = param_arr[i].name;
            input.value = param_arr[i].value;
            form.appendChild(input);
        }
        var script = document.createElement("script");
        script.src = "submitSpawnFormScript.js";
        html.appendChild(form);
        html.appendChild(script);
        content.appendChild(html)

        doc.open(); // oder einfach doc.appendChild(form);?
        doc.writeln(content.innerHTML);
        doc.close();
                
        //doc.reload(true);
    }
    else {
        // Einfach iframe.src = url?

    }
}


function processStatistic() {
    /**************************************************************************************************************************
    * Compute a statistic object that shows how often each sign of a sessionID is used within the captured probe of sessionIDs
    * returns associative array of the form ["a":count_a, ... , "z": count_z, ....]
    **************************************************************************************************************************/
    var stat = {"total":0};
    var sessid_arr = id("spawn_results").value.toString().split("\r\n");
    var i,j;
    var char;
    for(i = 0; i < sessid_arr.length; i++) {
        sessid_arr[i] = jQuery.trim(sessid_arr[i]); // Whitespace bei php session ID am Ende?!
        for (j = 0; j < sessid_arr[i].length; j++ ) {
            char = sessid_arr[i].toString().substr(j, 1);
            if (stat[char] !== undefined) {
                stat[char]++;
            }
            else {
                stat[char] = 1;
            }
            stat["total"]++;
        }
    }
            
    return stat;
}

function checkByteDistribution() {
    /*********************************************************************************************************
    * Check if the bytes from the captured sessionIDs are uniformly distributed, do statistical analysis
    * Draw the distribution in a html 5 canvas:
    * Compute for each sign in the alphabet for the sessionids the occurence in the set of captured sessionids
    * if uniformly distributed, these occurences shouldnt differ to much for each sign
    * -> draw bar diagram with percentage value for each sign 
    * compute graph fully dynamic for the alphabet that is observed, via associative array
    **********************************************************************************************************/
    var canvas = document.createElement("canvas");
    canvas.height = 560;
    id("canvas_div").innerHTML = "";
    id("canvas_div").appendChild(canvas);

    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "black";

    var stat = processStatistic();
    var i
    var n = 0;
    var max = 0;
            
    for (i in stat ) {
        if (i == "total") {
            continue;
        }
        n++;
        if (stat[i] > max) {
            max = stat[i];
        }
    }

    var x_step = 35;
            
    canvas.width = (x_step * n);
    var norm = (canvas.height-60) / max; // Balkenlaenge auf 500 pixel normieren
    ctx.beginPath();
    ctx.moveTo(1, canvas.height-30);
    ctx.lineTo(canvas.width, canvas.height-30);
    ctx.stroke();

    var c = 0;
    var entropy = 0;
    var p = 0;
    var keys = [];
    for (var k in stat) {
        keys.push(k);
        console.log(k);
    }
    keys.sort();

    for (j = 0; j < keys.length; j++) {
        i = keys[j];
        if (i == "total") {
            continue;
        }

        p = (stat[i] / stat["total"]); // probability of sign i in this probe
        if(p > 0) {
            entropy += p * Math.log(p);
        }

        ctx.fillStyle = "green";
        ctx.font = "10px sans-serif";
        ctx.fillRect(x_step*c,canvas.height - parseInt(norm * stat[i]) - 30 ,20,  parseInt(norm * stat[i]));
        ctx.fill();
        ctx.fillText((p * 100).toFixed(2) + "%", x_step * c, (canvas.height - parseInt(norm * stat[i]) - 30) - 10);

        ctx.beginPath();
        ctx.moveTo(x_step * c, canvas.height-30);
        ctx.lineTo(x_step * c, canvas.height-25);
        ctx.stroke();

        ctx.fillStyle = "black";
        ctx.font = "15px sans-serif";
        ctx.fillText(i, x_step * c, canvas.height-10);
        c++;
    }
    entropy *= -1;
    var entropy_max = Math.log(n);
    /*var entropy_max = 0;
    for(i = 0; i < n; i++) {
        entropy_max += (1/n)*Math.log(1/n);
    }
    entropy_max *= -1;*/
    font = document.createElement("font");
    font.color = "red";
    font.innerHTML = "<br />Source entropy: " + entropy + "<br />";
    font.innerHTML += "Maximal entropy: " + entropy_max + "<br />";
    font.innerHTML += "Normalized entropy: " + entropy/entropy_max;
    // whitespace am Ende jeder PHPSESSID verfaelscht die entropie?
    id("canvas_div").appendChild(font);
}


window.onload = function () {
    //DOM processing goes here
    id("session_url_display").value = url;
    id("session_url_display").size = url.length;
    id("sessionid_spawn_button").onclick = function () {
    	bg().HSTS_Header = null;
		bg().capture_HSTS_Header(url);
		var cookie_secure_warning = false;
		var cookie_domain_warning = false;
		var HSTS_header_warning = false;
    	spawnSessionIDs();
    };
    id("stop_spawning_button").onclick = stopSpawning;
    id("session_id_name_font").innerText = sessionid_name;
    id("check_distribution_button").onclick = checkByteDistribution;
}